<template>
    <z-paging 
        ref="paging" 
        @scroll="handleScroll"
        class="cart-container"
        :scroll-with-animation="true"
    >
        <!-- sku弹窗组件 -->
        <vk-data-goods-sku-popup 
            v-model="isShowSku"
            :mask-close-able="false"
            :localdata="goodsSkuList"
            :selected-init="true"
            :mode="2"
            add-cart-text="确定"
            add-cart-background-color="#008000"
            :actived-style="{
            color: '#008000',
            borderColor: '#008000',
            backgroundColor: '#D1F7D1'
            }"
            ref="goodsSkuPoup"
            @add-cart="onComfirmSelectSku"
            @open="onOpenSkuPopup"
        />

        <!-- 骨架屏区域 -->
        <view style="background-color: #fff;margin: 20rpx 10rpx;padding: 20rpx;" v-if="isShowSkeleton" v-for="(item, index) in 4" :key="index">
            <uv-skeletons :loading="isShowSkeleton" :skeleton="skeleton"></uv-skeletons>
        </view>

        <!-- 商品列表区域 -->
        <view class="cart-list" v-if="cartStore.validList.length > 0" :style="'padding-bottom: ' + paddingBottom">
            <!-- 购物车明细 -->
            <!-- 滑动操作分区 -->
            <uni-swipe-action>
                <uni-swipe-action-item v-for="(item, index) in cartStore.validList" :key="index">
                    <view class="cart-item">
                        <!-- 勾选框 -->
                        <view class="left">
                            <text class="icon iconfont" @click="checkOne(item.id, item.is_checked)" 
              :class="item.is_checked == 1 ? 'icon-xuanzhong checked' : 'icon-weixuanzhong'"></text>
                        </view>

                        <!-- 商品图片 -->
                        <view class="middle">
                            <!-- #ifdef MP-WEIXIN -->
                            <image :lazy-load="true" @click="toGoodsDetail(item.goods_id)" mode="aspectFill" class="cover" :src="global.FILE_DOMAIN + item.goods.cover_url" />
                            <!-- #endif -->

                            <!-- #ifdef H5 -->
                            <img @click="toGoodsDetail(item.goods_id)" class="cover" :src="global.FILE_DOMAIN + item.goods.cover_url" />
                            <!-- #endif -->
                        </view>

                        <!-- 商品信息 -->
                        <view class="right">
                            <view class="right-top ellipsis-2">{{ item.goods.name }}</view>
                            <view class="goods-sku" @click="selectGoodsSku(item)">
                                <text class="sku-left ellipsis-2">{{ item.goods_sepc_option_text }}</text>
                                <text class="icon iconfont icon-xiajiantou"></text>
                            </view>
                            <view class="right-bottom">
                                <!-- 商品价格 -->
                                <view class="price-box">
                                    <text class="symbol">￥</text>
                                    <text class="price">{{ (item.new_price/100).toFixed(2).split('.')[0] }}</text>
                                    <text class="decimal" v-if="(item.new_price/100).toFixed(2).split('.').length > 1">.{{ (item.new_price/100).toFixed(2).split('.')[1] }}</text>
                                    <text class="decimal" v-else>.00</text>
                                </view>

                                <!-- 商品数量 -->
                                <view class="option">
                                    <uni-number-box background="#008000" color="#fff" :min="1" :value="item.num" :max="item.inventory_num" @change="changeNum($event, item)"></uni-number-box>
                                </view>
                            </view>

                            <!-- 降价提醒 -->
                            <view class="goods-mark-down" v-if="index == 1">
                                <text>比加入时降价</text>
                                <text class="mark-down-value">
                                    ￥100.00
                                </text>
                            </view>
                        </view>
                    </view>
                    <!-- 右侧删除按钮 -->
                    <template #right>
                        <view class="cart-swipe-right">
                            <button @click="deleteCartGoods(item)" class="button delete-button">删除</button>
                        </view>
                    </template>
                </uni-swipe-action-item>
            </uni-swipe-action>

            <!-- 底部区域 -->
            <view class="footer">
                <view class="left">
                    <text class="icon iconfont" @click="checkAll" :class="cartStore.isCheckAll ? 'checked icon-xuanzhong ' : 'icon-weixuanzhong'"></text>
                    <text class="all">全选</text>
                </view>
                <view class="right">
                    <text class="heji">合计：</text>
                    <view class="price-box">
                        <text class="symbol">￥</text>
                        <text class="price">{{ (cartStore.checkedAmount/100).toFixed(2) }}</text>
                    </view>
                    <button class="pay-btn" @click="handlerSettle">去结算({{ cartStore.checkedTotal }})搜</button>
                </view>
            </view>
        </view>
         <!-- 购物车空状态 -->
         <view class="cart-blank" v-else>
            <image src="@/static/images/blank_cart.png" class="blank-image" />
            <text class="txt">购物车还是空的，快来挑选好货吧</text>
            <navigator open-type="switchTab" url="/pages/index/index" hover-class="none">
                <button class="btn">去首页看看</button>
            </navigator>
        </view>
    </z-paging>

    <!-- 返回顶部 -->
    <TridentFreshBackTop @backTop="backTop" :isShowBackTop="isShowBackTop"/>
</template>

<script setup lang="ts">
import { reqGetGoodsSkuListAPI } from '@/apis/goods';
import { onShow } from '@dcloudio/uni-app';
import { ref, inject, reactive } from 'vue';
import { useCartStore, useUserStore } from '@/stores'

const props = defineProps({
    'mode': {
        type: Number,
        default: 1
    }
})


// ----------------- 定义全局变量开始 -----------------
// 全局属性
const global:any = inject('global')

// 购物车存储
const cartStore = useCartStore()

// 用户存储
const userStore = useUserStore()

const paging = ref()

const paddingBottom = ref('260rpx;')
// ----------------- 定义全局变量结束 -----------------



// ----------------- 商品SKU功能开始 -----------------
// 是否显示SKU弹窗
const isShowSku = ref(false)

// 组装的商品SKU列表
const goodsSkuList = ref({})

// 原始的商品SKU列表
const goodsSkus = ref([])

// 商品SKU弹层
const goodsSkuPoup = ref()

// 当前SKU
const currentSku = ref([])

// 当前购物车商品信息
const currentCartGood:any = ref({})

// 选择商品SKU
const selectGoodsSku = async (good:any) => {
  // 设置当前购物车商品
  currentCartGood.value = good

  // 获取商品SKU数据
  const result:any = await reqGetGoodsSkuListAPI({goods_id: good.goods_id, is_have_goods_option: 1, page_size: -1})

  // 商品SKU
  goodsSkus.value = result.data.goods_sku_items != null ? result.data.goods_sku_items.filter((item:any) => item.inventory_num > 0 && item.status == 1) : []
  

  // 商品选项
  let goodsOptions = result.data.goods_options != null ? result.data.goods_options.reverse() : []

  // 组装商品SKU列表
  goodsSkuList.value = {
    _id: good.goods_id,
    name: good.goods.name,
    goods_thumb: global.FILE_DOMAIN + good.goods.cover_url,
    // sku_name_arr的数据顺序一定要和spec_list的数据顺序一致，坑坑坑的一逼
    // sku_name_arr ['荔枝纹杏色5.5cm', '38'] 与 spec_list {name: '颜色分类', list: Array(1)}{name: '尺码', list: Array(1)}
    sku_list: goodsSkus.value.map((item:any) => {
        // 如果商品SKU没有图片则使用商品封面图片
        let imgUrl =  item.img_url ? item.img_url : good.goods.cover_url
        return {
          _id: item.id,
          goods_id: good.goods_id,
          goods_name: good.goods.name,
          image: global.FILE_DOMAIN + imgUrl,
          img: imgUrl,
          price: item.price,
          sku_name_arr: item.spec_option_value_items,
          stock: item.inventory_num,
        }
    }),
    spec_list: goodsOptions.map((item:any) => {
      let valueList:any = []
      let values = item.value.split(',')
      values.forEach((v:any) => {
        valueList.push({name: v})
      });
      return {
        name: item.name,
        list: valueList
      }
    }),
  }

  // 组装当前SKU值
  let goodsSepcOptions = good.goods_sepc_option_text.trim().split(' ')

  // 重置当前SKU值
  currentSku.value = []
  
  goodsSepcOptions.forEach((v:any) => {
    currentSku.value.push(v.split('：')[1] as never)
  });

  // 将是否显示SKU设置为 true
  isShowSku.value = true
}

// 当sku弹层打开的时候执行，默认选中SKU选项
const onOpenSkuPopup = () => {
  goodsSkuPoup.value.selectSku({
    sku: currentSku.value,
    num: currentCartGood.value.num
  })
}

// 确定选择SKU
const onComfirmSelectSku = async (e:any) => {
  // 组装specsText
  let specsText = ''
  let goodsSku:any = goodsSkus.value.find((item:any) => item.id == e._id)
  if (goodsSku) {
    goodsSku.spec_option_values.forEach((v:any) => {
      specsText += v.name + "：" + v.value + " "
    });
  }
  
  // 如果sku选项没有变化，则不需要更新操作
  if (currentCartGood.value.goods_sku_id != e._id || currentCartGood.value.num != e.buy_num) {
    await cartStore.editCartSku({
      id: currentCartGood.value.id,
      num: e.buy_num,
      goods_cover_url: e.img,
      goods_name: e.goods_name,
      newSku: {
        skuId: e._id,
        price: e.price, 
        goods_cover_url: e.img,
        inventory_num: e.stock,
        specsText,
      }
    })
  }
  
  // 关闭SKU弹窗
  isShowSku.value = false
  uni.showToast({
    title: '选择SKU成功',
    duration: 1000
  })
}
// ----------------- 商品SKU功能结束 -----------------



// ----------------- 定义骨架变量开始 -----------------
// 定义是否显示骨架
const isShowSkeleton = ref(false)

// 定义骨架参数
const skeleton = reactive([
    {
        type: 'flex',
        num: 1,
        style: 'marginBottom: 20rpx;align-items: center;',
        children: [
            {
                type: 'custom',
                num: 1,
                style: 'width: 40rpx;height:40rpx;border-radius: 20rpx;'
            },
            {
                type: 'custom',
                num: 1,
                style: 'width: 200rpx;height:200rpx;marginLeft: 10rpx;marginRight: 20rpx;'
            },
            {
                type: 'line',
                num: 3,
                gap: '30rpx',
                style: [null, null, 'height:60rpx']
            },
        ]
    },
    {
        type: 'flex',
        num: 1,
        style: 'justify-content: flex-end;align-items: center;',
        children: [
            {
                type: 'custom',
                num: 1,
                style: 'width: 160rpx;height:40rpx;margin-right: 40rpx;'
            },
            {
                type: 'custom',
                num: 1,
                style: 'width: 50rpx;height:50rpx;'
            },
            {
                type: 'custom',
                num: 1,
                style: 'width: 80rpx;height:50rpx;margin: 0 10rpx'
            },
            {
                type: 'custom',
                num: 1,
                style: 'width: 50rpx;height:50rpx;'
            },
        ]
    }
])
// ----------------- 定义骨架变量结束 -----------------



// ----------------- 返回顶部功能开始 -----------------
// 定义是否显示返回顶部
const isShowBackTop = ref(false)

const backTop = () => {
    paging.value.scrollToTop()
}

// 当滚动触发时，调用事件用于显示、隐藏返回顶部图标
const handleScroll = (e:any) => {
    isShowBackTop.value = e.detail.scrollTop > 300 ? true : false
}
// ----------------- 返回顶部功能结束 -----------------



// -------------- 获取购物车列表功能开始 --------------
onShow(async () => {
    // #ifdef H5
    if (props.mode == 2) {
        paddingBottom.value = '170rpx;'
    }
    // #endif

    // #ifndef H5
    paddingBottom.value = '80rpx;'
    // #endif


    // 显示骨架
    isShowSkeleton.value = true

    // 刷新TOKEN
    await userStore.refreshToken('/pages/cart/index')

    if (userStore.profile?.token) {
        await cartStore.getCartList()
    } else {
        uni.redirectTo({ url: '/pages/password_login/index' })
    }

    // 隐藏骨架
    isShowSkeleton.value = false
})
// -------------- 获取购物车列表功能结束 --------------



// -------------- 删除购物车商品功能开始 --------------
const deleteCartGoods = (item:any) => {
	uni.showModal({
	    content: '确定要删除该商品吗?',
	    success: async (res) => {
	        if (res.confirm) {
            await cartStore.deleteCart(item.id)
            uni.showToast({
              title: '删除商品成功',
              duration: 1000
            })
	        }
	    }
	})
}
// -------------- 删除购物车商品功能结束 --------------



// ----------------- 修改数量功能开始 -----------------
const changeNum = async (num:any, item:any) => {
  // 如果未修改数量，则不需要发送请求
  if (num == item.num) {
    return false
  }

  // 判断库存
  if (num > item.inventory_num) {
    uni.showToast({
      icon: "none",
      title: '库存不足!',
      duration: 1000
    })

    return
  }
  
	await cartStore.editCart({ids: item.id + '', num})
	uni.showToast({
		title: '修改数量成功',
		duration: 1000
	})
}
// ----------------- 修改数量功能结束 -----------------



// ----------------- 勾选商品功能开始 -----------------
// 延时器
const timer:any = ref(null)

// 单选商品
const checkOne =  (id:any, checked:any) => {
	// ------------------ 防抖处理 ------------------
	// 清除延时器
	clearTimeout(timer.value)
	// 重新启动延时器
	timer.value = setTimeout( async () => {
		await cartStore.editCart({ids: id + '', is_checked: checked == 1 ? 0 : 1})
		uni.showToast({
			title: '编辑购物车成功',
			duration: 1000
		})
	}, 500)
}
// ----------------- 勾选商品功能结束 -----------------



// ----------------- 全选商品功能结束 -----------------
const checkAll = async () => {
  if (cartStore.validList.length == 0) {
    return false
  }
  
	await cartStore.checkAllCart(!cartStore.isCheckAll)
}
// ----------------- 全选商品功能结束 -----------------



// ----------------- 跳转详情功能开始 -----------------
const toGoodsDetail = (goodsId:any) => {
	uni.navigateTo({
		url:"/pagesGoods/goods_detail/index?id=" + goodsId
	})
}
// ----------------- 跳转详情功能结束 -----------------



// ----------------- 结算跳转功能结束 -----------------
const handlerSettle = () => {
	if (cartStore.checkedTotal <= 0) {
        uni.showToast({
        icon: 'none',
            title: '请勾选要结算的商品',
            duration: 1000
        })

        return
	}
	
	uni.navigateTo({
		url:"/pagesOrder/confirm_order/index?mode=2"
	})
}
// ----------------- 结算跳转功能结束 -----------------
</script>
<style scoped lang="scss">
.cart-container {
    height: 100vh;
    background-color: #FAF5F5;
    padding: 0 10rpx 0 10rpx;

    // 购物车列表区域
    .cart-list {
        position: relative;
        padding-top: 20rpx;
        // .cart-swipe {
        //     display: block;
            .cart-item {
                display: flex;
                align-items: center;
                background-color: #fff;
                border-radius: 10rpx;
                padding: 30rpx 25rpx 20rpx 25rpx;

                margin-bottom: 20rpx;
                .left {
                    width: 60rpx;
                    .icon {
                        font-size: 40rpx;
                        color: #ccc;
                    }
                    .checked {
                        color: #008000;
                    }
                }
                .middle {
                    width: 200rpx;
                    height: 200rpx;
                    border: 2rpx solid #ccc;
                    .cover {
                        width: 100%;
                        height: 100%;
                    }
                }
                .right {
                    flex: 1;
                    padding-left: 15rpx;
                    .right-top {
                        font-size: 32rpx;
                    }
                    .goods-sku {
                        margin: 20rpx 0;
                        background-color: #F7F7F8;
                        border: 2rpx dashed #ccc;
                        // height: 80rpx;
                        border-radius: 5rpx;
                        font-size: 24rpx;
                        color: gray;
                        padding: 10rpx;

                        display: flex;
                        justify-content: space-between;

                        .sku-left {
                            flex: 1;
                        }
                        .icon {
                            width: 30rpx;
                            color: gray;
                            font-size: 24rpx;
                        }
                    }
                    .right-bottom {
                        height: 50rpx;
                        line-height: 50rpx;
                        display: flex;
                        justify-content: space-between;

                        .price-box {
                            .symbol {
                                color: #CD0011;
                                font-size: 24rpx;
                            }
                            .price {
                                color: #CD0011;
                                font-size: 36rpx;
                            }
                            .decimal {
                                color: #CD0011;
                                font-size: 24rpx;
                            }
                        }
                    }

                    .goods-mark-down {
                        margin-top: 10rpx;
                        display: flex;
                        justify-content: flex-end;
                        font-size: 24rpx;
                        color: #CD0011;
                    }
                }
            }

            .cart-swipe-right {
                display: flex;
                height: 94%;

                .button {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    width: 50px;
                    padding: 6px;
                    line-height: 1.5;
                    color: #fff;
                    font-size: 26rpx;
                    border-radius: 0;
                }

                .delete-button {
                    background-color: #cf4444;
                }
            }
        // }

        .footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #fff;

            position: fixed;
            bottom: calc(var(--window-bottom));
            left: 0;
            height: 90rpx;
            width: 100%;
            padding: 0 20rpx 0 35rpx;
            border-bottom: 4rpx solid #ccc;
            z-index: 100;

            .left {
                .icon {
                    font-size: 40rpx;
                }
                .all {
                    margin-left: 10rpx;
                }
                .checked {
                    color: #008000;
                }
            }
            .right {
                display: flex;
                align-items: center;
                .price-box {
                    .symbol {
                        color: #CD0011;
                        font-size: 24rpx;
                    }
                    .price {
                        color: #CD0011;
                        margin-right: 10rpx;
                        font-size: 36rpx;
                    }
                }
                .pay-btn {
                    width: 160rpx;
                    height: 60rpx;
                    line-height: 60rpx;
                    background-color: #CD0011;
                    color: #fff;
                    font-size: 24rpx;
                    border-radius: 30rpx;
                }
            }
        }
    }

    // 空购物车区域
    .cart-blank {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding-top: 200rpx;
        font-size: 24rpx;
        .blank-image {
            width: 80%;
        }
        .txt {
            color: #ccc;
            margin: 30rpx 0;
        }
        .btn {
            background-color: #008000;
            color: #fff;
            font-size: 24rpx;
        }
    }
}
</style>